package com.example.dl645.protocol.factory;

import com.example.dl645.protocol.strategy.MeterParseStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 电表解析策略工厂
 */
@Component
public class MeterParseStrategyFactory {
    private final Map<String, MeterParseStrategy> strategyMap;
    @Autowired
    public MeterParseStrategyFactory(List<MeterParseStrategy> strategies) {
        this.strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        s -> bytesToHex(s.getDataIdentifier()),
                        s -> s
                ));
    }

    /**
     * 根据数据标识（大端序）获取解析策略
     */
    public MeterParseStrategy getStrategy(byte[] dataIdBigEndian) {
        String key = bytesToHex(dataIdBigEndian);
        return strategyMap.get(key);
    }
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}